package com.campsys.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin(origins = "http://localhost:8080")
@RequestMapping("/api")
public class UploadController {

    // 定义图片存储路径（可以根据需要修改）
    private static String UPLOADED_FOLDER = "picture/";

    @PostMapping("/upload")
    public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            Map<String, String> errorMap = new HashMap<>();
            errorMap.put("error", "请选择一个文件上传");
            return new ResponseEntity<>(errorMap, HttpStatus.BAD_REQUEST);
        }

        try {
            // 获取文件名
            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
            Files.write(path, bytes);

            Map<String, String> responseMap = new HashMap<>();
            responseMap.put("message", "文件上传成功: " + file.getOriginalFilename());
            responseMap.put("filePath", path.toString());

            return new ResponseEntity<>(responseMap, HttpStatus.OK);

        } catch (IOException e) {
            e.printStackTrace();
            Map<String, String> errorMap = new HashMap<>();
            errorMap.put("error", "文件上传失败: " + e.getMessage());
            return new ResponseEntity<>(errorMap, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
